﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class CharsAjaxDropdownController : Controller
    {
        private readonly IRepo<Person> r;

        public CharsAjaxDropdownController(IRepo<Person> r)
        {
            this.r = r;
        }

        public ActionResult GetItems(int? key, string code)
        {
            var list = new List<SelectListItem> { new SelectListItem { Text = "not selected", Value = "" } };
            var source = r.GetAll().Where(o =>o.Show != null && o.Show.Name == code);
            
            list.AddRange(source.Select(o => new SelectListItem
            {
                Text = o.FirstName + " " + o.LastName,
                Value = o.Id.ToString(),
                Selected = o.Id == key
            }));
            return Json(list);
        }
    }
    public class PersonAjaxDropdownController : Controller
    {
        private readonly IRepo<Person> repo;

        public PersonAjaxDropdownController(IRepo<Person> repo)
        {
            this.repo = repo;
        }

        public ActionResult GetItems(int? key, int? parent, IEnumerable<int> hobbeez, int? country)
        {
            var list = new List<SelectListItem> {new SelectListItem {Text = "not selected", Value = ""}};
            var source = repo.GetAll();
            
            if (parent.HasValue) source = source.Where(o => o.Show != null && o.Show.Id == parent);
                if (hobbeez != null) source = source.Where(o => o.Hobbies != null && o.Hobbies.Select(h => h.Id).Intersect(hobbeez).Count() == 0);
            if (country.HasValue) source = source.Where(o => o.Country != null && o.Country.Id == country);
            
            list.AddRange(source.Select(o => new SelectListItem
            {
                Text = o.FirstName + " " + o.LastName,
                Value = o.Id.ToString(),
                Selected = o.Id == key
            }));
            return Json(list);
        }
    }
}